import React, { useState, useEffect, useRef } from 'react';
import {
  Card,
  Table,
  Row,
  Col,
  Statistic,
  Space,
  Input,
  Select,
  Button,
  Modal,
  Form,
  Tag,
  Popconfirm,
  message,
  Drawer,
  Divider,
  AutoComplete,
  Switch,
  InputNumber,
  Tooltip
} from 'antd';
import {
  ShareAltOutlined,
  NodeIndexOutlined,
  BranchesOutlined,
  PlusOutlined,
  SearchOutlined,
  FilterOutlined,
  UploadOutlined,
  DownloadOutlined,
  EditOutlined,
  DeleteOutlined,
  EyeOutlined,
  SwapOutlined,
  SettingOutlined,
  ExclamationCircleOutlined
} from '@ant-design/icons';
import ReactECharts from 'echarts-for-react';
import { relationApi, entityApi } from '../../../services/api';
import relationTypeApi from '../../../services/relationTypeApi';
import ColorPicker from '../../../components/ColorPicker';

const { Search } = Input;
const { Option } = Select;
const { confirm } = Modal;

const RelationManagement = () => {
  const [relations, setRelations] = useState([]);
  const [loading, setLoading] = useState(false);
  const [searchText, setSearchText] = useState('');
  const [filterType, setFilterType] = useState('all');
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [isDrawerVisible, setIsDrawerVisible] = useState(false);
  const [editing, setEditing] = useState(null);
  const [current, setCurrent] = useState(null);
  const [form] = Form.useForm();

  // 分页参数
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0
  });

  // 统计数据
  const [statsData, setStatsData] = useState({
    relationCount: 0,
    entityCount: 0,
    typeCount: 0
  });

  // 类型分布数据
  const [typeDistributionData, setTypeDistributionData] = useState([]);

  // 活跃度趋势数据
  const [activityTrendData, setActivityTrendData] = useState({});
  const [timeDimension, setTimeDimension] = useState('周');

  // 空的关系类型分布数据（当后端数据不可用时使用）
  const emptyTypeDistribution = [];

  // 文件上传引用
  const fileInputRef = useRef(null);

  // 实体列表和搜索状态
  const [entities, setEntities] = useState([]);
  const [sourceOptions, setSourceOptions] = useState([]);
  const [targetOptions, setTargetOptions] = useState([]);
  const [sourceSearchValue, setSourceSearchValue] = useState('');
  const [targetSearchValue, setTargetSearchValue] = useState('');
  
  // 关系类型列表（用于过滤）
  const [relationTypeList, setRelationTypeList] = useState([]);
  
  // 关系类型管理状态
  const [isTypeModalVisible, setIsTypeModalVisible] = useState(false);
  const [relationTypes, setRelationTypes] = useState([]);
  const [typeLoading, setTypeLoading] = useState(false);
  const [typePagination, setTypePagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0
  });
  const [typeSearchText, setTypeSearchText] = useState('');
  const [currentType, setCurrentType] = useState(null);
  const [typeForm] = Form.useForm();
  const [selectedTypeKeys, setSelectedTypeKeys] = useState([]);
  const [isEditTypeModalVisible, setIsEditTypeModalVisible] = useState(false);

  // 获取实体列表
  const fetchEntities = async () => {
    try {
      const response = await entityApi.getEntities({
        page: 1,
        pageSize: 1000,
        onlyCurrentUser: true
      });
      
      if (response && response.success && response.data) {
        const entityList = response.data.data || [];
        setEntities(entityList);
      }
    } catch (error) {
      console.error('获取实体列表失败:', error);
    }
  };

  // 获取关系类型列表
  const fetchRelationTypes = async (params = {}) => {
    try {
      setTypeLoading(true);
      const queryParams = {
        page: params.page || typePagination.current,
        pageSize: params.pageSize || typePagination.pageSize,
        searchText: params.searchText !== undefined ? params.searchText : typeSearchText,
        onlyCurrentUser: false
      };

      const response = await relationTypeApi.getRelationTypes(queryParams);
      
      if (response && response.success) {
        const { data, total, current, pageSize } = response.data;
        setRelationTypes(data || []);
        setTypePagination({
          current: current || 1,
          pageSize: pageSize || 10,
          total: total || 0
        });
      } else {
        message.error(response?.message || '获取关系类型列表失败');
      }
    } catch (error) {
      console.error('获取关系类型列表失败:', error);
      message.error('网络错误，无法获取关系类型列表');
    } finally {
      setTypeLoading(false);
    }
  };

  // 获取关系列表
  const fetchRelations = async (params = {}) => {
    try {
      setLoading(true);
      // 合并查询参数
      const queryParams = {
        page: params.page || pagination.current,
        pageSize: params.pageSize || pagination.pageSize,
        searchText,
        type: filterType !== 'all' ? filterType : undefined,
        ...params
      };
      
      console.log('发送请求参数:', queryParams);
      const response = await relationApi.getRelations(queryParams);
      console.log('关系列表响应:', response);
      
      if (response && response.success && response.data) {
        const { data: relationList, total, current, pageSize } = response.data;
        
        // 格式化数据
        const formattedRelations = relationList.map(relation => ({
          id: relation.id,
          sourceEntity: relation.sourceEntity?.name || `实体ID: ${relation.sourceEntityId}`, 
          targetEntity: relation.targetEntity?.name || `实体ID: ${relation.targetEntityId}`,
          sourceEntityId: relation.sourceEntityId,
          targetEntityId: relation.targetEntityId,
          relationType: relation.type || '',
          description: relation.description || '',
          strength: relation.weight || 0.5,
          properties: relation.properties || {},
          createTime: relation.createTime ? new Date(relation.createTime).toLocaleString() : '',
          updateTime: relation.updateTime ? new Date(relation.updateTime).toLocaleString() : ''
        }));
        
        setRelations(formattedRelations);
        setPagination({
          current: current || 1,
          pageSize: pageSize || 10,
          total: total || 0
        });
        
        // 提取所有不重复的关系类型，用于过滤
        const types = [...new Set(formattedRelations.map(r => r.relationType))].filter(Boolean);
        setRelationTypeList(types.map(type => ({
          value: type,
          label: type,
          color: getRelationTypeColor(type)
        })));
      } else {
        message.error(response?.message || '获取关系列表失败');
        setRelations([]);
      }
    } catch (error) {
      console.error('获取关系列表失败:', error);
      message.error('网络错误，无法获取关系列表');
      setRelations([]);
    } finally {
      setLoading(false);
    }
  };

  // 获取统计数据
  const fetchStats = async () => {
    try {
      console.log('获取统计数据...');
      const response = await relationApi.getUserStats();
      console.log('统计数据响应:', response);
      
      if (response && response.success && response.data) {
        // 设置基础统计数据
        setStatsData({
          relationCount: response.data.relationCount || 0,
          entityCount: response.data.entityCount || 0,
          typeCount: response.data.typeCount || 0
        });
        
        // 设置类型分布数据
        setTypeDistributionData(response.data.typeDistribution || []);
        
        // 设置活跃度趋势数据
        setActivityTrendData(response.data.activityTrend || {});
      } else {
        message.error(response?.message || '获取统计数据失败');
      }
    } catch (error) {
      console.error('获取统计数据失败:', error);
      message.error('网络错误，无法获取统计数据');
    }
  };

  // 初始化加载
  useEffect(() => {
    fetchRelations();
    fetchStats();
    fetchEntities();
    fetchRelationTypes();
  }, []);

  // 搜索或筛选条件变化时重新加载
  useEffect(() => {
    fetchRelations({ page: 1 }); // 重置到第一页
  }, [searchText, filterType]);

  // 根据输入搜索源实体
  const handleSourceSearch = (value) => {
    setSourceSearchValue(value);
    if (!value) {
      setSourceOptions([]);
      return;
    }
    
    const filteredEntities = entities.filter(entity => 
      entity.name && entity.name.toLowerCase().includes(value.toLowerCase())
    );
    
    const options = filteredEntities.map(entity => ({
      value: entity.id.toString(),
      label: (
        <div style={{ display: 'flex', justifyContent: 'space-between' }}>
          <span>{entity.name}</span>
          <span style={{ color: '#999' }}>{entity.type}</span>
        </div>
      ),
      entity: entity
    }));
    
    setSourceOptions(options);
  };

  // 根据输入搜索目标实体
  const handleTargetSearch = (value) => {
    setTargetSearchValue(value);
    if (!value) {
      setTargetOptions([]);
      return;
    }
    
    const filteredEntities = entities.filter(entity => 
      entity.name && entity.name.toLowerCase().includes(value.toLowerCase())
    );
    
    const options = filteredEntities.map(entity => ({
      value: entity.id.toString(),
      label: (
        <div style={{ display: 'flex', justifyContent: 'space-between' }}>
          <span>{entity.name}</span>
          <span style={{ color: '#999' }}>{entity.type}</span>
        </div>
      ),
      entity: entity
    }));
    
    setTargetOptions(options);
  };

  // 表格分页、排序、筛选变化时的回调
  const handleTableChange = (pagination) => {
    setPagination(pagination);
    fetchRelations({
      page: pagination.current,
      pageSize: pagination.pageSize
    });
  };

  // 获取关系类型的颜色
  const getRelationTypeColor = (type) => {
    // 先从关系类型列表中查找
    const typeObj = relationTypes.find(t => t.typeName === type);
    if (typeObj) {
      return typeObj.color;
    }
    
    // 如果没有找到，使用默认颜色映射
    const colorMap = {
      '属于': '#1890ff',
      '工作于': '#52c41a',
      '位于': '#faad14',
      '相关于': '#722ed1',
      '部分于': '#f5222d',
      '使用': '#13c2c2',
      '创建': '#eb2f96',
      '管理': '#fa8c16'
    };
    
    // 如果没有预定义颜色，生成随机颜色
    if (!colorMap[type]) {
      // 使用类型字符串生成一个稳定的随机颜色（相同类型总是得到相同颜色）
      const hash = Array.from(type || '').reduce((acc, char) => {
        return char.charCodeAt(0) + ((acc << 5) - acc);
      }, 0);
      
      // 将哈希值转换为HSL颜色，保持饱和度和亮度适中，只改变色相
      const h = Math.abs(hash) % 360;
      const s = 65 + (Math.abs(hash) % 20); // 65%-85%饱和度
      const l = 45 + (Math.abs(hash) % 15); // 45%-60%亮度
      
      return `hsl(${h}, ${s}%, ${l}%)`;
    }
    
    return colorMap[type];
  };

  // 获取关系类型配置
  const getRelationTypeConfig = (type) => {
    return { 
      label: type || '未知关系', 
      color: getRelationTypeColor(type) 
    };
  };

  // 统计卡片数据
  const stats = [
    { 
      title: '关系总数', 
      value: statsData.relationCount, 
      icon: <ShareAltOutlined style={{ color: '#1890ff' }} />, 
      color: '#1890ff' 
    },
    { 
      title: '实体连接数', 
      value: statsData.entityCount, 
      icon: <NodeIndexOutlined style={{ color: '#52c41a' }} />, 
      color: '#52c41a' 
    },
    { 
      title: '关系类型数', 
      value: statsData.typeCount, 
      icon: <BranchesOutlined style={{ color: '#faad14' }} />, 
      color: '#faad14' 
    }
  ];

  const filtered = relations.filter(item => {
    const okSearch = searchText === '' || 
                    (typeof item.sourceEntity === 'string' && item.sourceEntity.includes(searchText)) || 
                    (typeof item.targetEntity === 'string' && item.targetEntity.includes(searchText)) || 
                    (typeof item.description === 'string' && item.description.includes(searchText));
    const okType = filterType === 'all' || item.relationType === filterType;
    return okSearch && okType;
  });

  const columns = [
    {
      title: '源实体',
      dataIndex: 'sourceEntity',
      width: 120,
      render: text => <Tag color="blue">{text}</Tag>
    },
    {
      title: '关系',
      dataIndex: 'relationType',
      width: 100,
      align: 'center',
      render: (type, record) => (
        <div style={{ textAlign: 'center' }}>
          <div style={{ color: '#666', fontSize: '12px' }}>{record.sourceEntity}</div>
          <SwapOutlined style={{ color: getRelationTypeConfig(type).color, margin: '4px 0' }} />
          <div style={{ color: '#666', fontSize: '12px' }}>{record.targetEntity}</div>
          <Tag color={getRelationTypeConfig(type).color} size="small">
            {getRelationTypeConfig(type).label}
          </Tag>
        </div>
      )
    },
    {
      title: '目标实体',
      dataIndex: 'targetEntity',
      width: 120,
      render: text => <Tag color="green">{text}</Tag>
    },
    {
      title: '描述',
      dataIndex: 'description',
      ellipsis: true
    },
    {
      title: '强度',
      dataIndex: 'strength',
      width: 80,
      align: 'center',
      render: strength => (
        <div>
          <div style={{ 
            width: '100%', 
            height: '6px', 
            backgroundColor: '#f0f0f0', 
            borderRadius: '3px',
            marginBottom: '4px'
          }}>
            <div style={{ 
              width: `${strength * 100}%`, 
              height: '100%', 
              backgroundColor: strength > 0.8 ? '#52c41a' : strength > 0.6 ? '#faad14' : '#ff4d4f',
              borderRadius: '3px'
            }} />
          </div>
          <div style={{ fontSize: '12px', textAlign: 'center' }}>{strength}</div>
        </div>
      )
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
      width: 150,
      render: time => <span style={{ color: '#666', fontSize: '12px' }}>{time}</span>
    },
    {
      title: '操作',
      width: 120,
      render: (_, record) => (
        <Space size="small">
          <EyeOutlined 
            style={{ color: '#1890ff', cursor: 'pointer' }}
            onClick={() => { setCurrent(record); setIsDrawerVisible(true); }} 
          />
          <EditOutlined 
            style={{ color: '#faad14', cursor: 'pointer' }}
            onClick={() => {
              setEditing(record);
              form.setFieldsValue({
                ...record,
                sourceEntityId: record.sourceEntityId?.toString(),
                targetEntityId: record.targetEntityId?.toString()
              });
              setIsModalVisible(true);
            }} 
          />
          <Popconfirm title="确认删除此关系？" onConfirm={() => handleDelete(record.id)}>
            <DeleteOutlined style={{ color: '#ff4d4f', cursor: 'pointer' }} />
          </Popconfirm>
        </Space>
      )
    }
  ];

  // 添加关系
  const handleAdd = () => {
    setEditing(null);
    form.resetFields();
    form.setFieldsValue({ strength: 0.5 });
    setIsModalVisible(true);
  };

  // 保存关系
  const handleSave = async () => {
    try {
      const values = await form.validateFields();
      setLoading(true);
      
      console.log('保存关系数据:', values);
      
      // 查找源实体和目标实体的名称
      const sourceEntity = entities.find(e => e.id.toString() === values.sourceEntityId.toString());
      const targetEntity = entities.find(e => e.id.toString() === values.targetEntityId.toString());
      
      let response;
      if (editing) {
        // 更新关系
        const updateData = {
          id: editing.id,
          name: `${sourceEntity?.name || ''} ${values.relationType} ${targetEntity?.name || ''}`,
          type: values.relationType,
          description: values.description,
          sourceEntityId: parseInt(values.sourceEntityId),
          targetEntityId: parseInt(values.targetEntityId),
          weight: parseFloat(values.strength)
        };
        
        response = await relationApi.updateRelation(updateData);
        console.log('更新响应:', response);
      } else {
        // 创建新关系
        const createData = {
          name: `${sourceEntity?.name || ''} ${values.relationType} ${targetEntity?.name || ''}`,
          type: values.relationType,
          description: values.description,
          sourceEntityId: parseInt(values.sourceEntityId),
          targetEntityId: parseInt(values.targetEntityId),
          weight: parseFloat(values.strength)
        };
        
        response = await relationApi.createRelation(createData);
        console.log('创建响应:', response);
      }
      
      if (response && response.success) {
        message.success(response.message || (editing ? '更新成功' : '添加成功'));
        setIsModalVisible(false);
        fetchRelations(); // 重新加载数据
        fetchStats();    // 更新统计数据
      } else {
        message.error(response?.message || '操作失败');
      }
    } catch (error) {
      if (error.errorFields) {
        // 表单验证错误
        return;
      }
      console.error('保存失败:', error);
      message.error(error.message || '操作失败');
    } finally {
      setLoading(false);
    }
  };

  // 删除关系
  const handleDelete = async (id) => {
    try {
      setLoading(true);
      console.log('删除关系:', id);
      const response = await relationApi.deleteRelation(id);
      console.log('删除响应:', response);
      
      if (response && response.success) {
        message.success(response.message || '删除成功');
        fetchRelations(); // 重新加载数据
        fetchStats();    // 更新统计数据
      } else {
        message.error(response?.message || '删除失败');
      }
    } catch (error) {
      console.error('删除失败:', error);
      message.error(error.message || '删除失败');
    } finally {
      setLoading(false);
    }
  };

  // 批量删除关系
  const handleBatchDelete = async () => {
    if (!selectedRowKeys.length) return;
    
    try {
      setLoading(true);
      console.log('批量删除关系:', selectedRowKeys);
      const response = await relationApi.batchDeleteRelations(selectedRowKeys);
      console.log('批量删除响应:', response);
      
      if (response && response.success) {
        message.success(response.message || `成功删除 ${selectedRowKeys.length} 条记录`);
        setSelectedRowKeys([]);
        fetchRelations(); // 重新加载数据
        fetchStats();    // 更新统计数据
      } else {
        message.error(response?.message || '批量删除失败');
      }
    } catch (error) {
      console.error('批量删除失败:', error);
      message.error(error.message || '批量删除失败');
    } finally {
      setLoading(false);
    }
  };

  // 导入关系
  const handleImport = () => {
    fileInputRef.current?.click();
  };

  // 处理文件上传
  const handleFileUpload = async (e) => {
    const file = e.target.files[0];
    if (!file) return;
    
    // 检查文件类型
    if (!file.name.endsWith('.xlsx') && !file.name.endsWith('.csv')) {
      message.error('只支持 Excel(.xlsx) 或 CSV(.csv) 文件');
      return;
    }
    
    try {
      setLoading(true);
      console.log('导入文件:', file.name);
      const response = await relationApi.importRelations(file);
      console.log('导入响应:', response);
      
      if (response && response.success) {
        message.success(response.message || '导入成功');
        fetchRelations(); // 重新加载数据
        fetchStats();    // 更新统计数据
      } else {
        message.error(response?.message || '导入失败');
      }
    } catch (error) {
      console.error('导入失败:', error);
      message.error(error.message || '导入失败');
    } finally {
      setLoading(false);
      // 重置文件输入，以便可以重新选择同一个文件
      if (fileInputRef.current) {
        fileInputRef.current.value = '';
      }
    }
  };

  // 导出关系
  const handleExport = async () => {
    try {
      setLoading(true);
      
      // 构建导出参数
      const exportParams = {
        searchText,
        type: filterType !== 'all' ? filterType : undefined,
        selectedIds: selectedRowKeys.length > 0 ? selectedRowKeys : undefined
      };
      
      console.log('导出参数:', exportParams);
      const blob = await relationApi.exportRelations(exportParams);
      
      // 创建下载链接
      const url = window.URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.download = `关系数据_${new Date().toISOString().split('T')[0]}.xlsx`;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      window.URL.revokeObjectURL(url);
      
      message.success('导出成功');
    } catch (error) {
      console.error('导出失败:', error);
      message.error(error.message || '导出失败');
    } finally {
      setLoading(false);
    }
  };

  // 渲染类型分布图表
  const renderTypeDistributionChart = () => {
    const chartData = typeDistributionData.length > 0 ? typeDistributionData : emptyTypeDistribution;
    
    return (
      <Row>
        <Col span={14}>
          <ReactECharts
            option={{
              tooltip: {
                trigger: 'item',
                formatter: '{a} <br/>{b}: {c} ({d}%)'
              },
              series: [
                {
                  name: '关系类型',
                  type: 'pie',
                  radius: ['45%', '75%'],
                  center: ['50%', '50%'],
                  avoidLabelOverlap: false,
                  itemStyle: {
                    borderRadius: 8,
                    borderColor: '#fff',
                    borderWidth: 2
                  },
                  label: {
                    show: false
                  },
                  emphasis: {
                    itemStyle: {
                      shadowBlur: 10,
                      shadowOffsetX: 0,
                      shadowColor: 'rgba(0, 0, 0, 0.5)'
                    }
                  },
                  labelLine: {
                    show: false
                  },
                  data: chartData.map(item => ({
                    value: item.value,
                    name: item.type,
                    itemStyle: {
                      color: item.color
                    }
                  }))
                }
              ]
            }}
            style={{ height: '280px' }}
          />
        </Col>
        <Col span={10}>
          <div style={{ paddingLeft: '20px', paddingTop: '40px' }}>
            {chartData.map((item, index) => (
              <div key={index} style={{ 
                display: 'flex', 
                alignItems: 'center', 
                marginBottom: '16px',
                fontSize: '13px'
              }}>
                <div style={{
                  width: '12px',
                  height: '12px',
                  borderRadius: '50%',
                  backgroundColor: item.color,
                  marginRight: '8px',
                  flexShrink: 0
                }} />
                <div style={{ 
                  flex: 1,
                  display: 'flex',
                  justifyContent: 'space-between',
                  alignItems: 'center'
                }}>
                  <span style={{ color: '#666' }}>{item.type}</span>
                  <span style={{ 
                    fontWeight: 'bold',
                    color: '#333',
                    marginLeft: '8px'
                  }}>
                    {item.value}%
                  </span>
                </div>
              </div>
            ))}
          </div>
        </Col>
      </Row>
    );
  };

  // 渲染活跃度趋势图表
  const renderActivityTrendChart = () => {
    // 使用后端数据
    const trendData = activityTrendData[timeDimension];
    
    // 如果没有数据，显示空状态
    if (!trendData || !trendData.categories || !trendData.barData) {
      return (
        <div style={{ 
          display: 'flex', 
          alignItems: 'center', 
          justifyContent: 'center', 
          height: '300px',
          color: '#999',
          fontSize: '14px'
        }}>
          暂无数据
        </div>
      );
    }
    
    // 准备图表数据
    const categories = trendData.categories || [];
    const barData = trendData.barData || [];
    const lineData = trendData.lineData || [];
    
    return (
      <ReactECharts
        option={{
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'cross',
              crossStyle: {
                color: '#999'
              }
            }
          },
          legend: {
            data: ['新增关系', '活跃度'],
            bottom: 0,
            textStyle: { fontSize: 11 }
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '15%',
            top: '10%',
            containLabel: true
          },
          xAxis: [
            {
              type: 'category',
              data: categories,
              axisPointer: {
                type: 'shadow'
              },
              axisLabel: { fontSize: 11 }
            }
          ],
          yAxis: [
            {
              type: 'value',
              name: '新增关系',
              position: 'left',
              axisLabel: {
                fontSize: 11,
                formatter: '{value}'
              }
            },
            {
              type: 'value',
              name: '活跃度',
              position: 'right',
              axisLabel: {
                fontSize: 11,
                formatter: '{value}'
              }
            }
          ],
          series: [
            {
              name: '新增关系',
              type: 'bar',
              yAxisIndex: 0,
              itemStyle: {
                borderRadius: [4, 4, 0, 0],
                color: {
                  type: 'linear',
                  x: 0,
                  y: 0,
                  x2: 0,
                  y2: 1,
                  colorStops: [
                    {
                      offset: 0,
                      color: '#1890ff'
                    },
                    {
                      offset: 1,
                      color: '#69c0ff'
                    }
                  ]
                }
              },
              data: barData
            },
            {
              name: '活跃度',
              type: 'line',
              yAxisIndex: 1,
              smooth: true,
              lineStyle: {
                width: 3,
                color: '#722ed1'
              },
              itemStyle: {
                color: '#722ed1'
              },
              symbol: 'circle',
              symbolSize: 6,
              data: lineData
            }
          ]
        }}
        style={{ height: '300px' }}
      />
    );
  };


  return (
    <div className="relation-management">
      {/* 统计卡片 */}
      <Row gutter={16} style={{ marginBottom: '16px' }}>
        {stats.map((stat, index) => (
          <Col span={8} key={index}>
            <Card>
              <Statistic 
                title={stat.title}
                value={stat.value}
                valueStyle={{ color: stat.color }}
                prefix={stat.icon}
              />
            </Card>
          </Col>
        ))}
      </Row>

      {/* 图表和工具栏 */}
      <Row gutter={16} style={{ marginBottom: '16px' }}>
        <Col span={12}>
          <Card title="关系类型分布" bordered={false}>
            {renderTypeDistributionChart()}
          </Card>
        </Col>
        <Col span={12}>
          <Card 
            title="关系增长趋势" 
            bordered={false}
            extra={
              <Select 
                value={timeDimension} 
                onChange={setTimeDimension}
                style={{ width: 100 }}
              >
                <Option value="周">近7天</Option>
                <Option value="月">近30天</Option>
                <Option value="年">近一年</Option>
              </Select>
            }
          >
            {renderActivityTrendChart()}
          </Card>
        </Col>
      </Row>

      {/* 工具栏 */}
      <Card style={{ marginBottom: '16px' }}>
        <Row gutter={16} align="middle">
          <Col span={8}>
            <Search
              placeholder="搜索关系..."
              value={searchText}
              onChange={e => setSearchText(e.target.value)}
              onSearch={value => setSearchText(value)}
              style={{ width: '100%' }}
              prefix={<SearchOutlined />}
              allowClear
            />
          </Col>
          <Col span={6}>
            <Select
              placeholder="按类型筛选"
              value={filterType}
              onChange={setFilterType}
              style={{ width: '100%' }}
              prefix={<FilterOutlined />}
              allowClear
            >
              <Option value="all">全部类型</Option>
              {relationTypeList.map(type => (
                <Option key={type.value} value={type.value}>
                  <Tag color={type.color}>{type.label}</Tag>
                </Option>
              ))}
            </Select>
          </Col>
          <Col span={10} style={{ textAlign: 'right' }}>
            <Space>
              <Button 
                type="primary" 
                icon={<PlusOutlined />}
                onClick={handleAdd}
              >
                添加关系
              </Button>
              <Button 
                icon={<SettingOutlined />}
                onClick={() => setIsTypeModalVisible(true)}
              >
                关系类型
              </Button>
              <Button 
                icon={<UploadOutlined />}
                onClick={handleImport}
              >
                导入
              </Button>
              <Button 
                icon={<DownloadOutlined />}
                onClick={handleExport}
              >
                导出
              </Button>
              <Popconfirm 
                title={`确认删除选中的 ${selectedRowKeys.length} 条记录？`}
                disabled={selectedRowKeys.length === 0}
                onConfirm={handleBatchDelete}
              >
                <Button 
                  danger 
                  disabled={selectedRowKeys.length === 0}
                  icon={<DeleteOutlined />}
                >
                  批量删除
                </Button>
              </Popconfirm>
            </Space>
          </Col>
        </Row>
      </Card>

      {/* 数据表格 */}
      <Card>
        <Table
          rowKey="id"
          columns={columns}
          dataSource={filtered}
          loading={loading}
          pagination={{
            ...pagination,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条`,
            pageSizeOptions: ['10', '20', '50', '100'],
            showLessItems: true
          }}
          onChange={handleTableChange}
          rowSelection={{
            selectedRowKeys,
            onChange: keys => setSelectedRowKeys(keys)
          }}
          size="middle"
        />
      </Card>

      {/* 添加/编辑关系对话框 */}
      <Modal
        title={editing ? '编辑关系' : '添加关系'}
        open={isModalVisible}
        onOk={handleSave}
        onCancel={() => setIsModalVisible(false)}
        confirmLoading={loading}
        width={600}
      >
        <Form
          form={form}
          layout="vertical"
          initialValues={{ strength: 0.5 }}
        >
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="sourceEntityId"
                label="源实体"
                rules={[{ required: true, message: '请选择源实体' }]}
              >
                <AutoComplete
                  placeholder="搜索源实体..."
                  options={sourceOptions}
                  onSearch={handleSourceSearch}
                  onSelect={(value, option) => {
                    form.setFieldsValue({ 
                      sourceEntityId: value,
                      sourceEntity: option.entity.name
                    });
                  }}
                  style={{ width: '100%' }}
                />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="targetEntityId"
                label="目标实体"
                rules={[{ required: true, message: '请选择目标实体' }]}
              >
                <AutoComplete
                  placeholder="搜索目标实体..."
                  options={targetOptions}
                  onSearch={handleTargetSearch}
                  onSelect={(value, option) => {
                    form.setFieldsValue({ 
                      targetEntityId: value,
                      targetEntity: option.entity.name
                    });
                  }}
                  style={{ width: '100%' }}
                />
              </Form.Item>
            </Col>
          </Row>
          
          <Form.Item
            name="relationType"
            label="关系类型"
            rules={[{ required: true, message: '请输入关系类型' }]}
          >
            <Input placeholder="请输入关系类型，如：属于、工作于、位于等" />
          </Form.Item>
          
          <Form.Item
            name="description"
            label="描述"
          >
            <Input.TextArea rows={3} placeholder="请输入关系描述..." />
          </Form.Item>
          
          <Form.Item
            name="strength"
            label="关系强度"
            rules={[{ required: true, message: '请设置关系强度' }]}
          >
            <Input
              type="number"
              min={0}
              max={1}
              step={0.1}
              placeholder="0.0 - 1.0"
            />
          </Form.Item>
        </Form>
      </Modal>

      {/* 关系详情抽屉 */}
      <Drawer
        title="关系详情"
        placement="right"
        width={500}
        onClose={() => setIsDrawerVisible(false)}
        open={isDrawerVisible}
      >
        {current && (
          <>
            <div style={{ marginBottom: '24px' }}>
              <div style={{ 
                display: 'flex', 
                alignItems: 'center', 
                justifyContent: 'center',
                flexDirection: 'column',
                padding: '20px 0'
              }}>
                <div style={{ 
                  display: 'flex', 
                  alignItems: 'center', 
                  marginBottom: '16px'
                }}>
                  <Tag color="blue" style={{ fontSize: '14px', padding: '4px 8px' }}>
                    {current.sourceEntity}
                  </Tag>
                  <SwapOutlined style={{ 
                    margin: '0 12px', 
                    color: getRelationTypeConfig(current.relationType).color,
                    fontSize: '18px'
                  }} />
                  <Tag color="green" style={{ fontSize: '14px', padding: '4px 8px' }}>
                    {current.targetEntity}
                  </Tag>
                </div>
                <Tag color={getRelationTypeConfig(current.relationType).color} style={{ 
                  fontSize: '16px', 
                  padding: '4px 12px',
                  marginBottom: '8px'
                }}>
                  {getRelationTypeConfig(current.relationType).label}
                </Tag>
              </div>
              
              <Divider />
              
              <div style={{ marginBottom: '16px' }}>
                <div style={{ color: '#666', marginBottom: '8px' }}>描述</div>
                <div>{current.description || '无描述'}</div>
              </div>
              
              <div style={{ marginBottom: '16px' }}>
                <div style={{ color: '#666', marginBottom: '8px' }}>关系强度</div>
                <div>
                  <div style={{ 
                    width: '100%', 
                    height: '8px', 
                    backgroundColor: '#f0f0f0', 
                    borderRadius: '4px',
                    marginBottom: '8px'
                  }}>
                    <div style={{ 
                      width: `${current.strength * 100}%`, 
                      height: '100%', 
                      backgroundColor: current.strength > 0.8 ? '#52c41a' : current.strength > 0.6 ? '#faad14' : '#ff4d4f',
                      borderRadius: '4px'
                    }} />
                  </div>
                  <div style={{ textAlign: 'center' }}>{current.strength}</div>
                </div>
              </div>
              
              <Divider />
              
              <div style={{ marginBottom: '16px' }}>
                <div style={{ color: '#666', marginBottom: '8px' }}>创建时间</div>
                <div>{current.createTime || '未知'}</div>
              </div>
              
              <div style={{ marginBottom: '16px' }}>
                <div style={{ color: '#666', marginBottom: '8px' }}>更新时间</div>
                <div>{current.updateTime || '未知'}</div>
              </div>
              
              <Divider />
              
              <div style={{ marginBottom: '16px' }}>
                <div style={{ color: '#666', marginBottom: '8px' }}>属性</div>
                <div>
                  {Object.keys(current.properties || {}).length > 0 ? (
                    Object.entries(current.properties).map(([key, value], index) => (
                      <div key={index} style={{ 
                        display: 'flex', 
                        justifyContent: 'space-between',
                        marginBottom: '8px'
                      }}>
                        <span style={{ color: '#888' }}>{key}:</span>
                        <span>{value}</span>
                      </div>
                    ))
                  ) : (
                    <div style={{ color: '#999' }}>无自定义属性</div>
                  )}
                </div>
              </div>
            </div>
            
            <div style={{ 
              position: 'absolute', 
              bottom: 0, 
              width: '100%', 
              borderTop: '1px solid #e8e8e8', 
              padding: '10px 16px',
              textAlign: 'right',
              left: 0,
              background: '#fff'
            }}>
              <Space>
                <Button onClick={() => setIsDrawerVisible(false)}>关闭</Button>
                <Button 
                  type="primary" 
                  onClick={() => {
                    setEditing(current);
                    form.setFieldsValue({
                      ...current,
                      sourceEntityId: current.sourceEntityId?.toString(),
                      targetEntityId: current.targetEntityId?.toString()
                    });
                    setIsDrawerVisible(false);
                    setIsModalVisible(true);
                  }}
                >
                  编辑
                </Button>
              </Space>
            </div>
          </>
        )}
      </Drawer>

      {/* 关系类型管理模态框 */}
      <Modal
        title="关系类型管理"
        open={isTypeModalVisible}
        onCancel={() => setIsTypeModalVisible(false)}
        width={1000}
        footer={null}
      >
        <div style={{ marginBottom: 16 }}>
          <Row gutter={16} align="middle">
            <Col flex="auto">
              <Input.Search
                placeholder="搜索类型代码、名称或描述"
                value={typeSearchText}
                onChange={(e) => setTypeSearchText(e.target.value)}
                onSearch={() => fetchRelationTypes({ page: 1, searchText: typeSearchText })}
                style={{ width: 300 }}
                allowClear
              />
              <Button onClick={() => {
                setTypeSearchText('');
                fetchRelationTypes({ page: 1, searchText: '' });
              }} style={{ marginLeft: 8 }}>
                重置
              </Button>
            </Col>
            <Col>
              <Space>
                <Button
                  type="primary"
                  icon={<PlusOutlined />}
                  onClick={() => {
                    setCurrentType(null);
                    typeForm.resetFields();
                    typeForm.setFieldsValue({
                      enabled: true,
                      sortOrder: 0,
                      color: '#1890ff'
                    });
                    setIsEditTypeModalVisible(true);
                  }}
                >
                  添加类型
                </Button>
                <Button
                  danger
                  disabled={selectedTypeKeys.length === 0}
                  onClick={() => {
                    if (!selectedTypeKeys.length) return;

                    confirm({
                      title: '确认删除',
                      icon: <ExclamationCircleOutlined />,
                      content: `确定要删除选中的 ${selectedTypeKeys.length} 项吗？`,
                      onOk: async () => {
                        try {
                          setTypeLoading(true);
                          const response = await relationTypeApi.batchDeleteRelationTypes(selectedTypeKeys);
                          
                          if (response && response.success) {
                            message.success(response.message || `成功删除 ${selectedTypeKeys.length} 条记录`);
                            setSelectedTypeKeys([]);
                            fetchRelationTypes();
                          } else {
                            message.error(response?.message || '批量删除失败');
                          }
                        } catch (error) {
                          console.error('批量删除失败:', error);
                          message.error(error.message || '批量删除失败');
                        } finally {
                          setTypeLoading(false);
                        }
                      }
                    });
                  }}
                >
                  批量删除
                </Button>
              </Space>
            </Col>
          </Row>
        </div>

        <Table
          rowKey="id"
          columns={[
            {
              title: '类型代码',
              dataIndex: 'typeCode',
              width: 120,
              render: (text) => <span style={{ fontFamily: 'monospace' }}>{text}</span>
            },
            {
              title: '类型名称',
              dataIndex: 'typeName',
              width: 150,
              render: (text, record) => (
                <Tag color={record.color} style={{ fontSize: '14px', padding: '2px 8px' }}>
                  {text}
                </Tag>
              )
            },
            {
              title: '颜色',
              dataIndex: 'color',
              width: 80,
              render: (color) => (
                <div style={{ 
                  width: '24px', 
                  height: '24px', 
                  backgroundColor: color, 
                  borderRadius: '4px',
                  border: '1px solid #ddd'
                }} />
              )
            },
            {
              title: '描述',
              dataIndex: 'description',
              ellipsis: true
            },
            {
              title: '排序',
              dataIndex: 'sortOrder',
              width: 100,
              render: (sortOrder, record) => (
                <InputNumber
                  min={0}
                  max={999}
                  value={sortOrder}
                  onChange={async (value) => {
                    try {
                      setTypeLoading(true);
                      const response = await relationTypeApi.updateSortOrder(record.id, value);
                      
                      if (response && response.success) {
                        message.success(response.message || '更新排序成功');
                        fetchRelationTypes();
                      } else {
                        message.error(response?.message || '更新排序失败');
                      }
                    } catch (error) {
                      console.error('更新排序失败:', error);
                      message.error(error.message || '更新排序失败');
                    } finally {
                      setTypeLoading(false);
                    }
                  }}
                  style={{ width: '70px' }}
                />
              )
            },
            {
              title: '状态',
              dataIndex: 'enabled',
              width: 80,
              render: (enabled, record) => (
                <Switch
                  checked={enabled}
                  onChange={async (checked) => {
                    try {
                      setTypeLoading(true);
                      const response = await relationTypeApi.updateEnabled(record.id, checked);
                      
                      if (response && response.success) {
                        message.success(response.message || `${checked ? '启用' : '禁用'}成功`);
                        fetchRelationTypes();
                      } else {
                        message.error(response?.message || '操作失败');
                      }
                    } catch (error) {
                      console.error('操作失败:', error);
                      message.error(error.message || '操作失败');
                    } finally {
                      setTypeLoading(false);
                    }
                  }}
                  size="small"
                />
              )
            },
            {
              title: '创建时间',
              dataIndex: 'createTime',
              width: 180,
              render: (time) => time ? new Date(time).toLocaleString() : '-'
            },
            {
              title: '操作',
              width: 120,
              render: (_, record) => (
                <Space size="small">
                  <Tooltip title="编辑">
                    <Button 
                      type="text" 
                      icon={<EditOutlined />} 
                      onClick={() => {
                        setCurrentType(record);
                        typeForm.setFieldsValue({
                          ...record
                        });
                        setIsEditTypeModalVisible(true);
                      }}
                    />
                  </Tooltip>
                  <Tooltip title="删除">
                    <Popconfirm
                      title="确认删除此关系类型？"
                      onConfirm={async () => {
                        try {
                          setTypeLoading(true);
                          const response = await relationTypeApi.deleteRelationType(record.id);
                          
                          if (response && response.success) {
                            message.success(response.message || '删除成功');
                            fetchRelationTypes();
                          } else {
                            message.error(response?.message || '删除失败');
                          }
                        } catch (error) {
                          console.error('删除失败:', error);
                          message.error(error.message || '删除失败');
                        } finally {
                          setTypeLoading(false);
                        }
                      }}
                    >
                      <Button 
                        type="text" 
                        danger 
                        icon={<DeleteOutlined />} 
                      />
                    </Popconfirm>
                  </Tooltip>
                </Space>
              )
            }
          ]}
          dataSource={relationTypes}
          pagination={{
            ...typePagination,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条`,
            pageSizeOptions: ['10', '20', '50', '100'],
            showLessItems: true
          }}
          loading={typeLoading}
          onChange={(pagination) => {
            fetchRelationTypes({
              page: pagination.current,
              pageSize: pagination.pageSize
            });
          }}
          rowSelection={{
            selectedRowKeys: selectedTypeKeys,
            onChange: (keys) => setSelectedTypeKeys(keys)
          }}
          size="middle"
        />
      </Modal>

      {/* 添加/编辑关系类型表单 */}
      <Modal
        title={currentType ? '编辑关系类型' : '添加关系类型'}
        open={isEditTypeModalVisible}
        onOk={async () => {
          try {
            const values = await typeForm.validateFields();
            setTypeLoading(true);

            let response;
            if (currentType) {
              // 更新
              response = await relationTypeApi.updateRelationType({
                ...values,
                id: currentType.id
              });
            } else {
              // 创建
              response = await relationTypeApi.createRelationType(values);
            }

            if (response && response.success) {
              message.success(response.message || (currentType ? '更新成功' : '添加成功'));
              setIsEditTypeModalVisible(false);
              fetchRelationTypes();
            } else {
              message.error(response?.message || '操作失败');
            }
          } catch (error) {
            if (error.errorFields) {
              return;
            }
            console.error('保存失败:', error);
            message.error(error.message || '操作失败');
          } finally {
            setTypeLoading(false);
          }
        }}
        onCancel={() => setIsEditTypeModalVisible(false)}
        confirmLoading={typeLoading}
        maskClosable={false}
        width={600}
      >
        <Form
          form={typeForm}
          layout="vertical"
        >
          <Form.Item
            name="typeCode"
            label="类型代码"
            rules={[
              { required: true, message: '请输入类型代码' },
              { pattern: /^[a-z][a-z0-9_]*$/, message: '类型代码只能包含小写字母、数字和下划线，且必须以字母开头' }
            ]}
          >
            <Input placeholder="如：belongs_to" />
          </Form.Item>

          <Form.Item
            name="typeName"
            label="类型名称"
            rules={[{ required: true, message: '请输入类型名称' }]}
          >
            <Input placeholder="如：属于" />
          </Form.Item>

          <Form.Item
            name="color"
            label="类型颜色"
            rules={[{ required: true, message: '请选择类型颜色' }]}
          >
            <ColorPicker />
          </Form.Item>

          <Form.Item
            name="description"
            label="类型描述"
          >
            <Input.TextArea rows={3} placeholder="请输入类型描述" />
          </Form.Item>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="sortOrder"
                label="排序序号"
                rules={[{ required: true, message: '请输入排序序号' }]}
              >
                <InputNumber min={0} max={999} style={{ width: '100%' }} />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="enabled"
                label="是否启用"
                valuePropName="checked"
              >
                <Switch />
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </Modal>

      {/* 隐藏的文件上传输入 */}
      <input
        type="file"
        ref={fileInputRef}
        style={{ display: 'none' }}
        accept=".xlsx,.csv"
        onChange={handleFileUpload}
      />
    </div>
  );
};

export default RelationManagement;
